import 'dart:convert';
import 'dart:ui' as ui;

import 'package:douhuaxiangsu/widgets/toast.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

import '../entity/artwork_model.dart';
import '../utils/image_utils.dart';

/// 像素点样式选择弹窗组件
class PointStyleDialog extends StatefulWidget {
  final CanvasConfig canvasConfig;
  final Function() onStyleChanged;
  final BuildContext ctx;

  const PointStyleDialog({
    super.key,
    required this.canvasConfig,
    required this.onStyleChanged,
    required this.ctx,
  });

  @override
  State<PointStyleDialog> createState() => _PointStyleDialogState();
}

class _PointStyleDialogState extends State<PointStyleDialog> {
  late CanvasConfig canvasConfig;
  late final BuildContext ctx;

  @override
  void initState() {
    canvasConfig = widget.canvasConfig;
    ctx = widget.ctx;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('修改像素点样式'),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              title: const Text('正方形'),
              trailing: const Icon(Icons.square),
              onTap: () {
                _updatePointStyle('default', '1');
              },
            ),
            ListTile(
              title: const Text('圆形'),
              trailing: const Icon(Icons.circle),
              onTap: () {
                _updatePointStyle('default', '2');
              },
            ),
            ListTile(
              title: const Text('圆环'),
              trailing: const Icon(Icons.trip_origin),
              onTap: () {
                _updatePointStyle('default', '3');
              },
            ),
            ListTile(
              title: const Text('十字'),
              trailing: const Icon(Icons.close),
              onTap: () {
                _updatePointStyle('default', '4');
              },
            ),
            ListTile(
              title: const Text('自定义'),
              onTap: () {
                Navigator.of(context).pop();
                _selectCustomPointStyle();
              },
            ),
          ],
        ),
      ),
    );
  }

  /// 更新像素点样式
  void _updatePointStyle(String type, String data) {
    Navigator.of(context).pop();
    canvasConfig.pointStyle.type = type;
    canvasConfig.pointStyle.data = data;
    widget.onStyleChanged();
  }

  /// 选择自定义像素点样式
  Future<void> _selectCustomPointStyle() async {
    final ImagePicker picker = ImagePicker();
    try {
      final XFile? image = await picker.pickImage(source: ImageSource.gallery);

      if (image != null) {
        // 读取图片字节数据
        final bytes = await image.readAsBytes();
        final base64Image = base64Encode(bytes);
        if (!base64Image.startsWith('iVBOR')) {
          if (ctx.mounted) {
            Toast.show('仅支持PNG', ctx);
          }
          return;
        }
        // 将图片设置颜色蒙版
        ui.Image? img = await ImageUtils.loadImageFromBase64WithColor(
          base64Image,
          Colors.grey,
          width: 30,
          height: 30,
        );
        if (img == null) {
          if (ctx.mounted) {
            Toast.show('选择图片失败', ctx);
          }
          return;
        }
        var saveBase64 = await ImageUtils.imageToBase64(img);
        // 更新像素点样式
        canvasConfig.pointStyle.type = 'custom';
        canvasConfig.pointStyle.data = saveBase64 ?? base64Image;
        widget.onStyleChanged();
      }
    } catch (e) {
      if (ctx.mounted) {
        Toast.show('选择图片失败', ctx);
      }
      if (kDebugMode) {
        print('选择图片失败: $e');
      }
    }
  }
}
